/*
 * @(#)OrderServiceImplListener.java 2021年3月17日
 *
 * Copyright (c) 2010 by rayootech.com. All rights reserved.
 */
package com.nuctech.order.service.impl;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Service;

import com.nuctech.common.entity.Order;
import com.nuctech.common.entity.TxLog;
import com.nuctech.order.dao.TxLogDao;
import com.nuctech.order.service.OrderService;

import lombok.RequiredArgsConstructor;

/**
 * RocketMQTransactionListener
 * 
 * @author lilu
 * @date 2021年3月17日
 * @since 1.0.0
 */
@Service
@RocketMQTransactionListener
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@SuppressWarnings("rawtypes")
public class OrderServiceImplListener implements RocketMQLocalTransactionListener {
	
	private final TxLogDao txLogDao;
	
	private final OrderService orderService;

	// 执行本地事务
	@Override
	public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
		try {
			String txId = (String) msg.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
			Order order = (Order) arg;
			this.orderService.createOrderTx(order, txId);
			return RocketMQLocalTransactionState.COMMIT;
		} catch (Exception e) {
			return RocketMQLocalTransactionState.ROLLBACK;
		}
	}

	// 消息回查
	@Override
	public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
		String txId = (String) msg.getHeaders().get(RocketMQHeaders.TRANSACTION_ID);
		TxLog txLog = this.txLogDao.findById(txId).get();
		
		if (txLog != null) {
			// 本地事务成功
			return RocketMQLocalTransactionState.COMMIT;
		} else {
			return RocketMQLocalTransactionState.ROLLBACK;
		}
	}

}
